import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer1 {
    private ServerSocket serverSocket = null;

    public TcpEchoServer1(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void Start() throws IOException {
        System.out.println("服务器启动成功！");
        ExecutorService pool = Executors.newCachedThreadPool();
        while (true) {
            Socket socket = serverSocket.accept();
            pool.submit(() -> {
                connectProcess(socket);
            });
        }
    }

    public void connectProcess(Socket socket) {
        System.out.printf("[%s:%d]   客户端已上线...\n", socket.getInetAddress(), socket.getPort());
        try(InputStream inputStream=socket.getInputStream();
            OutputStream outputStream=socket.getOutputStream()){
            Scanner scanner=new Scanner(inputStream);
            PrintWriter writer=new PrintWriter(outputStream);
            while(true){
                if(!scanner.hasNext()){
                    System.out.printf("[%s:%d]   客户端下线...\n", socket.getInetAddress(), socket.getPort());
                }
                String request=scanner.next();
                String response=process(request);
                writer.println(response);
                writer.flush();
                //打印日志
                System.out.printf("[%s:%d]   req:%s    rep:%s\n", socket.getInetAddress(), socket.getPort(), request, response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer1 server1=new TcpEchoServer1(8080);
        server1.Start();
    }
}
